<?php
class Default_Service_Svc
{

	protected $_customerId = null;	 
	protected $_token = null;
	protected $_key = null;
	protected $_auth = false;
	protected $_error = null;
	
	public function createProduct($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		$sku = (string)$paramter->ProductInfo->sku;
		
		 
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','sku'=>$sku,'time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;
		
		}
		//$sku = (string)$paramter->ProductInfo->sku;
		$skuCNName = (string)$paramter->ProductInfo->skuCNName;
		$skuName = (string)$paramter->ProductInfo->skuName;
		$weight = (float)$paramter->ProductInfo->weight;		
       	$length = (float)$paramter->ProductInfo->length;		
       	$width = (float)$paramter->ProductInfo->width;
       	$height = (float)$paramter->ProductInfo->height;
		$declareValue = (float)$paramter->ProductInfo->declareValue;
		$categoryId = (int)$paramter->ProductInfo->categoryId;
		$package  = (int)$paramter->ProductInfo->package;
		$minQty = (int)$paramter->ProductInfo->minQty;
        if($package==0) $package = null;
		$image = $paramter->ProductInfo->image;
		$key = 0;
		if (count($image) > 1) {
			foreach ($image as $value) {
				$skuImg[$key] = $value->imgUrl;			
				$key ++;
			}		
		}elseif(count($image)==1){
			$skuImg[$key] = $image->imgUrl;			
		}
		//qc options
		$productIsQc = 0;//不需要QC
		$qcs = $paramter->ProductInfo->qcs;
		if(!isset($qcs)){
			$qcs = array();
		}
		$qcArr = array();
		if(count($qcs)>1){
			foreach($qcs as $v){				
				$qcArr[] = array('poc_id'=>$v->pocId,'po_id'=>'4','po_value'=>$v->poValue);
				if(empty($v->poValue)){
					$this->_error = "qc content empty";
					break;
				}
			}
			$productIsQc = 1;//需要QC
		}elseif(count($qcs)==1){
			$qcArr[] = array('poc_id'=>$qcs->pocId,'po_id'=>'4','po_value'=>$qcs->poValue);
			$productIsQc = 1;//需要QC
			if(empty($qcs->poValue)){
				$this->_error = "qc content empty";
			}
		}
		if(!empty($this->_error)){
			$result['message'] = $this->_error;
			return $result;
		}
// 		$result['message'] = print_r($qcArr,true);
// 		return $result;
		//目录
		$productOptionValues[] = array('poc_id'=>$categoryId,'po_id'=>'1');
		//最小库存
		$productOptionValues[] = array('poc_id'=>$minQty,'po_id'=>'3');
		
		$row = array(
						"product_title" => $skuName,//产品名称
						"product_title_cn" => $skuCNName,//产品中文名称
						"product_sku" =>$sku,//产品编号						 
						"product_weight" =>$weight,//产品重量
						"product_length" =>$length,//产品长
						"product_width" =>$width,//宽
						"product_height" =>$height,//高
						"product_declared_value" => $declareValue, //申报价值	
						"product_is_qc"=> $productIsQc  //				
					);
					
	    
		
		$serviceObj = new Merchant_Service_Product();
		$create = $serviceObj->create($row,$productOptionValues,null,$skuImg,$this->_customerId,$package,$qcArr);
		 
		if($create !== true){//创建失败
			$msg = null;			 
			foreach ($create as $val){
				$msg .= $val.';		';
			}
			$result['message'] = $msg;
			return $result;
		}
		$result['message'] = 'Success';
		$result['ask'] = 'Success';
		return $result;
	 
	}
	//更新产品  ---------图片、包材、是否每次QC、QC属性
	public function updateProduct($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;		
		$customerId  = (string)$paramter->HeaderRequest->customerId;
		$sku = (string)$paramter->ProductModifyInfo->sku;
			
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','sku'=>$sku,'time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;
	
		}
		
		$package  = (int)$paramter->ProductModifyInfo->package;
		$status  = (int)$paramter->ProductModifyInfo->status;
		$productIsQc = (int)$paramter->ProductModifyInfo->productIsQc;
		$image = $paramter->ProductModifyInfo->image;		
		//qc options
		$qcs = $paramter->ProductModifyInfo->qcs;
		
		
		
		if($package==0){
			$package = null;
		}
		
		if(!isset($image)){
			$image = array();
		}
		$key = 0;
		if (count($image) > 1) {
			foreach ($image as $value) {
				$skuImg[$key] = $value->imgUrl;
				$key ++;
			}
		}elseif(count($image)==1){
			$skuImg[$key] = $image->imgUrl;
		}	
		if(!isset($qcs)){
			$qcs = array();
		}
		$qcArr = array();
		if(count($qcs)>1){
			foreach($qcs as $v){
// 				$qcArr[] = array('poc_id'=>$v['pocId'],'po_id'=>'4','po_value'=>$v['poValue']);
				$qcArr[] = array('poc_id'=>$v->pocId,'po_id'=>'4','po_value'=>$v->poValue);
				if(empty($v->poValue)){
					$this->_error = "qc content empty";
					break;
				}
			}			
		}elseif(count($qcs)==1){
			$qcArr[] = array('poc_id'=>$qcs->pocId,'po_id'=>'4','po_value'=>$qcs->poValue);
			if(empty($qcs->poValue)){
				$this->_error = "qc content empty";				
			}
		}
		if(!empty($this->_error)){
			$result['message'] = $this->_error;
			return $result;
		}
		if(empty($qcArr)){
			$qcArr = null;
		}
		if(empty($skuImg)){
			$skuImg = null;
		}
		
		$row = array();		
		
		 if(isset($productIsQc)){
		 	$row["product_is_qc"] = $productIsQc;
		 }
		 
		$serviceObj = new Merchant_Service_Product();	
// 		$result['message'] = print_r($paramter,true);
// 		return $result;
		$r = $serviceObj->svcUpdate($sku,$row,$customerId,$skuImg,$package,$qcArr);	
		
		if($r !== true){//创建失败		
			$result['message'] = $r;
			return $result;
		}
		$result['message'] = 'Success';
// 		$result['message'] = 'Success'.print_r($row,true).print_r($paramter,true);
		$result['ask'] = 'Success';
		return $result;
	
	}

	public function getProductBySKU($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		$sku = (string)$paramter->sku;
		$detailLevel = (string)$paramter->detailLevel;
		 
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		$pObj = new Merchant_Service_Product();
		$productInfo = $pObj->getProductBySku($sku,$this->_customerId);
		 
		if(!$detailLevel) $detailLevel =0;
		if($detailLevel=='0'){
			$data = array(
						'sku'=>$productInfo['product_sku'],
						'productTitle'=>$productInfo['product_title'],
						'productAddTime'=>$productInfo['product_date_added'],
						'productLastModified'=>$productInfo['product_last_modified'],
						'productStatu'=>$productInfo['product_status']
					);
		
		
		}else{
			$stock = Merchant_Service_WarehouseProducts::getStockByProduct($productInfo['product_id']);
			$totalStock = 0; 
			$totalStockHold = 0;  
			foreach($stock as $key => $val){
				$warehouseInfo = array('warehouse'=>$val['warehouse'],'stock'=>$val['stock'],'stockOnHold'=>$val['stockOnHold']);
				$totalStock += $val['stock'];
				$totalStockHold += $val['stockOnHold'];
			}
			
		
			$data = array(
						'sku'=>$productInfo['product_sku'],
						'productTitle'=>$productInfo['product_title'],
						'productTitleCn'=>$productInfo['product_title_cn'],
						'productAddTime'=>$productInfo['product_date_added'],
						'productLastModified'=>$productInfo['product_last_modified'],
						'productStatu'=>$productInfo['product_status'],
						'productLength'=>$productInfo['product_length'],
						'productWidth'=>$productInfo['product_width'],
						'productHeight'=>$productInfo['product_height'],
						'productWeight'=>$productInfo['product_weight'],
						'declaredValue'=>$productInfo['product_declared_value'],
						'categoryId'=> $productInfo['category']['poc_id'],
						'category'=>$productInfo['category']['poc_value'],
						'warehouseInfo'=>$warehouseInfo	,
						'warehouseStock'=>$totalStock,
						'warehouseStockOnHold'=>$totalStockHold
					);
		
		
		}
		$result['ask'] = 'Success';
		$result['data'] = $data;
		return $result;
		
	
	}

	/*
	*
	*createASN
	*
	*/
	public function createASN($paramter){
		
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','ASNCode'=>'','time'=>$now);
		
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;
		}
        $orderType = (string)$paramter->ASNInfo->ASNType; //ASN类型
        $orderType=(!$orderType)?1:$orderType;
        if(!in_array($orderType, array("1","2"))){
            $result['message'] = 'ASNType can not found.';
            return $result;
        }

        if($orderType=='2'){
            $orderType=4;//特采
        }
		$receivingArr['ref_id'] = (string)$paramter->ASNInfo->referenceNo;
		$receivingArr['description'] = (string)$paramter->ASNInfo->instructions;
		$receivingArr['contact'] = (string)$paramter->ASNInfo->contact;//联系人 2012年7月14日
		$receivingArr['contact_mobile'] = (string)$paramter->ASNInfo->contactMobile;//联系方式 2012年7月14日
		$receivingArr['customer_id'] = $this->_customerId;
		$receivingArr['warehouse_id'] = 1;  	//只有一个仓库，ID为 1
		$receivingArr['order_type'] = (!$orderType) ? 1 : $orderType  ;		//默认为 1 ，标准
		$receivingArr['status'] = 1;
		$receivingArr['created'] = $now;
		$receivingArr['pickup'] = 0;		//暂时默认为0
		$receivingArr['supplier_id'] = '';
		
		
		$orderDetail = $paramter->ASNInfo->ASNDetail;
		
		$key = 0;
		$orderProduct = array();
		$chkArr = array();//qc
		$priorityArr = array();//优先级
		$productObj = new Merchant_Service_Product();
		if (count($orderDetail) > 1) {
			foreach ($orderDetail as $value) {
				if($value->sku){
					if(!isset($value->isQC)){//默认值
						$value->isQC=0;
					}
					if(!isset($value->priorityLevel)){//默认值
						$value->priorityLevel=0;
					}
					$product = $productObj->getProductBySku($value->sku,$this->_customerId);
					if(!$product){
						$result['message'] = 'SKU: '.$value->sku.'  can not found.';
						return $result;
					}
						
					$isQC = $value->isQC;
					if(!$value->isQC){
						$isQC = $product['product_is_qc']?1:0;
					}
                    //特采免检,需判断问题库存
                    if( $orderType==4){
                       $isQC=0;
                       $productStocketRow = Merchant_Service_ProductStocket::getByProductId($product['product_id'],1);
                       if(empty($productStocketRow) || $productStocketRow['ps_quantity_problem'] < $value->quantity ){
                           $result['message'] = "SKU:".$value->sku." problem quantity is ".(isset($productStocketRow['ps_quantity_problem'])?$productStocketRow['ps_quantity_problem']:0).", less than $value->quantity";
                           return $result;
                       }
                    }
		
					if($isQC){
						$pocArr = Merchant_Service_ProductOptionValue::getByProductId($product['product_id'],4);
						if(count($pocArr)==0){
							$result['message'] = 'SKU:'.$product['product_sku'].' qc items is null.';
							return $result;
						}
		
					}
						
						
					$chkArr+=array("{$product['product_id']}"=>$isQC);
					$priority = 0;
					if($value->priorityLevel){
						$priority = $value->priorityLevel;
					}
					$priorityArr+=array("{$product['product_id']}"=>$priority);
						
					$tmp = array("{$product['product_id']}"=> $value->quantity);
						
					$orderProduct += $tmp;//array_merge($orderProduct,);
						
				}else{
					$result['message'] = 'SKU can not be null.';
					return $result;
				}
				$key ++;
			}
		}elseif (count($orderDetail) == 1){
			if($orderDetail->sku){
				if(!isset($orderDetail->isQC)){//默认值
					$orderDetail->isQC=0;
				}
				if(!isset($orderDetail->priorityLevel)){//默认值
                    $orderDetail->priorityLevel=0;
				}
				$product = $productObj->getProductBySku($orderDetail->sku,$this->_customerId);
				if(!$product){
					$result['message'] = 'SKU: '.$orderDetail->sku.'  can not found.';
					return $result;
				}
				$isQC = $orderDetail->isQC;
				if(!$orderDetail->isQC){
					$isQC = $product['product_is_qc']?1:0;
				}
                //特采免检,需判断问题库存
                if( $orderType==4){
                    $isQC=0;
                    $productStocketRow = Merchant_Service_ProductStocket::getByProductId($product['product_id'],1);
                    if(empty($productStocketRow) || $productStocketRow['ps_quantity_problem'] < $orderDetail->quantity ){
                        $result['message'] = "SKU:".$orderDetail->sku." problem quantity is ".(isset($productStocketRow['ps_quantity_problem'])?$productStocketRow['ps_quantity_problem']:0).", less than $orderDetail->quantity";
                        return $result;
                    }
                }
				if($isQC){
					$pocArr = Merchant_Service_ProductOptionValue::getByProductId($product['product_id'],4);
					if(empty($pocArr)){
						$result['message'] = 'SKU:'.$product['product_sku'].' qc items is null...';
						return $result;
					}
				}
					
				$chkArr=array("{$product['product_id']}"=>$isQC);//qc
				$priority = 0;
				if($orderDetail->priorityLevel){
					$priority = $orderDetail->priorityLevel;
				}
				$priorityArr+=array("{$product['product_id']}"=>$priority);//priority
		
					
				$orderProduct = array("{$product['product_id']}"=>$orderDetail->quantity);
			}else{
				$result['message'] = 'SKU can not be null.';
				return $result;
			}
		
		}else{
			$result['message'] = 'Order Detail can not be null.';
			return $result;
		}
		
		$asnObj = new Merchant_Service_AsnProccess($orderType==4?'T':'R');
		$return = $asnObj->create($orderProduct,$receivingArr,$this->_customerId,$chkArr,$priorityArr);
		
		if($return['ask']!= 'Success'||!$return['ask']){
			$result['ask'] = 'Error';
			$result['message'] = $return['msg'];
			return $result;
		}
		$result['ask'] = 'Success';
		$result['ASNCode'] = $return['receiving_code'];
		$result['message'] = $return['msg'];
		return $result;
		
		
	}
	
	
	/*
	*deleteAsnProduct
	*
	*/
	public function deleteAsnProduct($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		$AsnCode = (string)$paramter->AsnCode;
		$skus = $paramter->Skus;
		 
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','AsnCode'=>$AsnCode,'time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		
		$proudctSKUs = array();
		if(count($skus)>1){
			foreach($skus as $v){
				$proudctSKUs[] = $v->sku;
			}
		}elseif(count($skus)==1){
			$proudctSKUs[] = $skus->sku;		
		}
// 		$str = $skus->sku;
// 		$proudctSKUs = explode(",", $str);
		
	
// 		$result['message'] = 	print_r($paramter,true);
// 		return $result;
		$proudctSKUs = array_unique($proudctSKUs);
		
		$pObj = new Merchant_Service_AsnProccess();
		$msg = $pObj->deleteAsnProduct($AsnCode,$proudctSKUs,$this->_customerId);
		
		if($msg!==true) {
			$result['message'] = $msg;
			return $result;
		}
		$result['ask'] = 'Success';	
		return $result;
	
	}
	
	/*
	 *getAsnInfo
	*
	*/
	public function getAsnInfo($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$AsnCode = (string)$paramter->AsnCode;
		$detailLevel = (string)$paramter->detailLevel;
			
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;
		}
		$pObj = new Merchant_Service_AsnProccess();
		$asnInfo = $pObj->getAsnInfo($AsnCode,$this->_customerId);
	
		if(!$asnInfo) {
			$result['message'] = 'Asn Code not found!';
		}
		$result['ask'] = 'Success';
		$result['data'] = $asnInfo;
		return $result;
	
	}
	/*
	 *updateAsnStatus
	*
	*/
	public function updateAsnStatus($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$AsnCode = (string)$paramter->AsnCode;
		$AsnStatus = (string)$paramter->AsnStatus;
			
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;
		}
		$pObj = new Merchant_Service_AsnProccess();
		$asnInfo = $pObj->getAsnInfo($AsnCode,$this->_customerId);
	
		if(!$asnInfo) {
			$result['message'] = 'Asn Code not found!';
			return $result;
		}
		
		$result['AsnCode'] = $asnInfo['AsnCode'];
		if($AsnStatus==$asnInfo['AsnStatu']){
			$result['message'] = 'Asn status is same!';
			return $result;
		}
		if(!in_array($AsnStatus, array("0","1"))||!in_array($asnInfo['AsnStatu'], array("0","1"))){
			$result['message'] = 'forbidden update,Asn is in operation!';
			return $result;
		}
		
		if($AsnStatus=="1"&&empty($asnInfo['AsnDetail'])){//变为确定状态 需要验证
			$result['message'] = 'asn item empty!';
			return $result;
		}
		$Obj = new Merchant_Model_Receiving();
		//将状态更新
		if(!$Obj->update(array('status'=>$AsnStatus), $asnInfo['AsnCode'],"receiving_code")){
			$result['message'] = 'Asn  delete fail';
		}else{
			$result['ask'] = 'Success';		
		}
		
		return $result;
	
	
	}
	/*
	 *updateAsn 
	 *更新receive:ref_id ,description
	 *更新receiveItem ：quantity,is_qc,ri_sort
	*
	*/
	public function updateASN($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$AsnCode = (string)$paramter->AsnCode;
		$skus = $paramter->ASNInfo->ASNDetail;
		 
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','AsnCode'=>$AsnCode,'time'=>$now);
        $this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		$receivingArr = array();
		$referenceNo = (string)$paramter->ASNInfo->referenceNo;
		$description = (string)$paramter->ASNInfo->instructions;
		
		$contact = (string)$paramter->ASNInfo->contact;//联系人 2012年7月14日
		$contactMobile = (string)$paramter->ASNInfo->contactMobile;//联系方式 2012年7月14日
		
		if($referenceNo){
			$receivingArr['ref_id'] = $referenceNo;
		}
				
		if($description){
			$receivingArr['description'] = $description;
		}
				
		$contact && $receivingArr['contact'] = $contact;
		$contactMobile && $receivingArr['contact_mobile'] = $contactMobile;
		
		
		$productObj = new Merchant_Service_Product();
		$receiveItem = array();
		if(count($skus)>1){
			foreach($skus as $v){
				$arr = array();				
				$arr['product_sku']= $v->sku;
				
				if(isset($v->quantity)&&!empty($v->quantity)){
					$arr['order_qty'] = (int)$v->quantity ;
				}
				if(isset($v->isQC)){
					$arr['is_qc'] = (int)$v->isQC ;
				}
				if(isset($v->priorityLevel)){
					$arr['ri_sort'] = (int)$v->priorityLevel ;
				}
				$receiveItem[] = $arr;
			}
		}elseif(count($skus)==1){
			$arr = array();
			
			$arr['product_sku']=$skus->sku;
			
			if(isset($skus->quantity)&&!empty($skus->quantity)){
				$arr['order_qty'] = (int)$skus->quantity ;
			}
			if(isset($skus->isQC)){
				$arr['is_qc'] = (int)$skus->isQC ;
			}
			if(isset($skus->priorityLevel)){
				$arr['ri_sort'] = (int)$skus->priorityLevel ;
			}
			$receiveItem[] = $arr;		
		}

		$proudctSKUs = array_unique($proudctSKUs);
		
// 		$result['message'] = print_r($paramter,true).$AsnCode.print_r($receivingArr,true).print_r($receiveItem,true).print_r($this->_customerId,true);
// 		return $result;
		
		$pObj = new Merchant_Service_AsnProccess();
		$msg = $pObj->updateReceive($AsnCode,$receivingArr,$receiveItem,$this->_customerId);
		
		if($msg!==true) {
			$result['message'] = $msg;
			return $result;
		}
		$result['ask'] = 'Success';	
		return $result;
	}
	/*
	*
	*updateProduct
	*
	*/
	public function updateProductStatu($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		$sku = (string)$paramter->sku;
		$statu = (string)$paramter->statu;
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','sku'=>$sku,'time'=>$now);
		$this->authenticate();
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		//:0删除,1已激活,2草稿
		$statArr = array(0,1,2);
		/*
		$productObj = new Merchant_Service_Product();
		$productInfo =	$productObj->getProductBySku($sku,$this->_customerId);
		
		
		if(!$productInfo||empty($productInfo)){
			$result['message'] = 'SKU:"'.$sku.'", Doesn\'t exist. ';
			return $result;		
		}
		*/
		if(!in_array($statu,$statArr)){
			$result['message'] = 'product statu is not allow. ';
			return $result;		
		}
		$pProc = new Merchant_Service_ProductProccess();
		$pProc->setProductBySku($sku,$this->_customerId);
		$return = $pProc->submited($statu);
		
		if($return['ask']=='Error'){
			
			$result['message'] = $return['msg'];
			return $result;
		}
		$result['message'] = 'Success';
		$result['ask'] = 'Success';
		return $result;
	 
	}
	/*
	*add orders
	*
	*/
	public function createOrder($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','orderCode'=>'','time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		$referenceNo = (string)$paramter->orderInfo->referenceNo;
		$consigneeFirstName = (string)$paramter->orderInfo->consigneeFirstName;
		$consigneeLastName = (string)$paramter->orderInfo->consigneeLastName;
		$consigneeCompany = (string)$paramter->orderInfo->consigneeCompany;		
       	$consigneeCountry = (string)$paramter->orderInfo->consigneeCountry;		
       	$shippingMethodCode = (string)$paramter->orderInfo->shippingMethodCode;
       	$consigneeZip = (string)$paramter->orderInfo->consigneeZip;
		$consigneeState = (string)$paramter->orderInfo->consigneeState;
		$consigneeCity = (string)$paramter->orderInfo->consigneeCity;
		$consigneeAddress1 = (string)$paramter->orderInfo->consigneeAddress1;
       	$consigneeAddress2 = (string)$paramter->orderInfo->consigneeAddress2;
		$consigneePhone = (string)$paramter->orderInfo->consigneePhone;
		
		$consigneeEmail = (string)$paramter->orderInfo->consigneeEmail;
       	$instructions = (string)$paramter->orderInfo->instructions;
		$orderStatu  =  (int)$paramter->orderInfo->orderStatu;
		
		//Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;
		$countryObj = new Default_Service_Country();
		$countryId = $countryObj->getIdByName($consigneeCountry);
		if(!$countryId){
			$result['message'] = 'Can not find this country.';
			return $result;
		}
        $shippingMethodCode = strtoupper($shippingMethodCode);
		$key = 0;		
		$productObj = new Merchant_Service_Product();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty  = 0;
		$weight =0;
		
		if (count($orderDetail) > 1) {
			foreach ($orderDetail as $value) {				 
				if($value->sku){
					$product = $productObj->getProductBySku($value->sku,$this->_customerId);
					
					if(!$product){
						$result['message'] = 'SKU: '.$value->sku.'  can not be found.';
						return $result;					
					}
					$op_category = 0;
					$cagetory = $productObj->getProductCategory($product['product_id']);
					if($cagetory){						
						$op_category = $cagetory['poc_id'];
					}
					$orderProduct[] =array(										    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $value->quantity,
										   'product_sku' => $product['product_sku'],
										   'op_description' => empty($value->opDescription)?"":$value->opDescription,
										   'cn_description' => empty($value->cnDescription)?"":$value->cnDescription,
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$value->quantity,2),
										   'op_declared_value' => round($product['product_declared_value']*$value->quantity,2),
										   'op_weight' => round($product['product_weight']*$value->quantity,4),
										   'op_category' => $op_category,
										);
					$weight += 	round($product['product_weight']*$value->quantity,4);					
					$declaredValue  += 	round($product['product_declared_value']*$value->quantity,2);				
					$parcelContents .=		$product['product_title'].';	';	
					$parcelQty +=	$value->quantity;
				}else{				
					$result['message'] = 'SKU can not be null.';
					return $result;				
				}				 
				$key ++;			
			}		
		}else{
				if($orderDetail->sku){
					$product = $productObj->getProductBySku($orderDetail->sku,$this->_customerId);
					if(!$product){
						$result['message'] = 'SKU: '.$orderDetail->sku.'  can not be found.';
						return $result;					
					}
					$op_category = 0;
					$cagetory = $productObj->getProductCategory($product['product_id']);
					if($cagetory){						
						$op_category = $cagetory['poc_id'];
					}
					$orderProduct[] =array(									    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $orderDetail->quantity,
										   'product_sku' => $product['product_sku'],										   
										   'op_description' => empty($orderDetail->opDescription)?"":$orderDetail->opDescription,
										   'cn_description' => empty($orderDetail->cnDescription)?"":$orderDetail->cnDescription,
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_declared_value' => round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_weight' => round($product['product_weight']*$orderDetail->quantity,4),
										   'op_category' => $op_category,
										);
					$weight += 	round($product['product_weight']*$orderDetail->quantity,4);					
					$declaredValue += round($product['product_declared_value']*$orderDetail->quantity,2);
					$parcelContents .= 	$product['product_title'];
					$parcelQty +=	$orderDetail->quantity;
				}else{
					$result['message'] = 'SKU can not be null.';
					return $result;
				}
			 
		}
		$shipMethod = Default_Service_ShipType::getByValue($shippingMethodCode,$field='st_code');
		if(!$shipMethod||$shipMethod['st_status']!='1'){
			$result['message'] = 'Shipping method is not Available.';
			return $result;
		}
		$options = array('warehouseId'=>1,
				'countryId'=>$countryId,
				'stId'=>$shipMethod['st_id'],
				'weight'=>$weight,
				'length'=>1,
				'width'=>1,
				'height'=>1,
				'customerId'=>$this->_customerId
		);
		$shipFeeObj = new Default_Service_ShipFeeCalc($options);
		$fee = $shipFeeObj->calcFeeByType();
		if(!is_array($fee)){
			$result['message'] = $fee;
			return $result;
		}
		
		 $orderInfo =array(             
            'customer_id' =>$this->_customerId,
            'consignee_address1' => $consigneeAddress1,
            'consignee_address2' =>$consigneeAddress2,
            'consignee_city' =>$consigneeCity,
            'consignee_company' =>$consigneeCompany,
            'consignee_country_id' =>$countryId,
            'consignee_email' =>$consigneeEmail,
            'consignee_first_name' =>$consigneeFirstName,
            'consignee_last_name' =>$consigneeLastName,
            'consignee_phone' =>$consigneePhone,
            'consignee_region' =>$consigneeState,
            'consignee_zip' => $consigneeZip,
            'customer_order_code' => $referenceNo,
            'parcel_contents' => $parcelContents,
            'parcel_declared_value' => $declaredValue,
            'parcel_quantity' => $parcelQty,
            'remark' => $instructions,
            'shipping_method' => $shippingMethodCode,
            'order_product' =>$orderProduct,
            'shipping_fee_estimate' =>$fee['inter_fee'],
        );
		//去除前后空格
		foreach($orderInfo as $k=>$v){
			if(!is_array($v)){
				$orderInfo[$k] = trim($v);
			}
		}
		
		$return = Merchant_Service_OrderProccess::addOrder($orderInfo);
		
// 		return $return;
		if($return['ask'] == false){
			$result['message'] = join('; ',$return['list']['error']);
			return $result;				
		}
		if(!$orderStatu) $orderStatu = 1;
		$orderCode = $return['ordersCode'];
		$arrStat = array('0','1','2','3');
		if(!in_array($orderStatu,$arrStat)){
			$result['message'] = 'Order status Can not be modify.';
			return $result;
		}
		if($orderStatu>'1'){//交寄订单
			$orderPocc = new Merchant_Service_OrderProccess($orderCode);
			$orderPocc->setCustomer($this->_customerId);
			$opStat = $orderPocc->submited($orderCode=null,$orderStatu);
			if($opStat['ask']!='Success'){
				$result['ask'] = 'SuccessWithWarning';			 
				$result['orderCode'] = $orderCode;	
				$result['message'] = 'Warning, change orders status failure, '.$opStat['msg'];
				return $result;	
			}
			
		}
		
		$result['ask'] = 'Success';
		$result['message'] = 'Successful';
		$result['orderCode'] = $orderCode;	 
		
		return $result;	
	}
	
	
	/*
	*add orders
	*
	*/
	public function createEspecialOrder($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
       	$this->_token = (string)$paramter->HeaderRequest->appToken;
       	$this->_key = (string)$paramter->HeaderRequest->appKey;
		
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','orderCode'=>'','time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		
		$referenceNo = (string)$paramter->orderInfo->referenceNo;
		$consigneeFirstName = (string)$paramter->orderInfo->consigneeFirstName;
		$consigneeLastName = (string)$paramter->orderInfo->consigneeLastName;
		$consigneeCompany = (string)$paramter->orderInfo->consigneeCompany;		
       	$consigneeCountry = (string)$paramter->orderInfo->consigneeCountry;		
       	$shippingMethodCode = (string)$paramter->orderInfo->shippingMethodCode;
       	$consigneeZip = (string)$paramter->orderInfo->consigneeZip;
		$consigneeState = (string)$paramter->orderInfo->consigneeState;
		$consigneeCity = (string)$paramter->orderInfo->consigneeCity;
		$consigneeAddress1 = (string)$paramter->orderInfo->consigneeAddress1;
       	$consigneeAddress2 = (string)$paramter->orderInfo->consigneeAddress2;
		$consigneePhone = (string)$paramter->orderInfo->consigneePhone;
		
		$consigneeEmail = (string)$paramter->orderInfo->consigneeEmail;
       	$instructions = (string)$paramter->orderInfo->instructions;
		$orderStatu  =  (int)$paramter->orderInfo->orderStatu;
		
		$orderContents = (string)$paramter->orderInfo->parcelContents;
		//Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;
		$countryObj = new Default_Service_Country();
		$countryId = $countryObj->getIdByName($consigneeCountry);
		if(!$countryId){
			$result['message'] = 'Can not find this country.';
			return $result;
		}
		
// 		$result['message'] = print_r($paramter->orderInfo,true);
// 		return $result;
		
		$regAccType = (string)$paramter->orderInfo->regAccType;
		$regAccount = (string)$paramter->orderInfo->regAccount;
		
		switch(strtolower($regAccType)){
			case 'ebay':
				$regAccType = 'ebay';
				break;
			case 'amazon':
				$regAccType = 'amazon';
				break;
			default:
				$regAccType = 'other';
				break;
		}
		
		$regArr = array('ori_account_type'=>$regAccType,'ori_ref_account'=>$regAccount);


        $shippingMethodCode = strtoupper($shippingMethodCode);
		$key = 0;		
		$productObj = new Merchant_Service_Product();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty  = 0;
		$weight =0;
		
	
		if (count($orderDetail) > 1) {
			foreach ($orderDetail as $value) {				 
				if($value->sku){
					$product = $productObj->getProductBySku($value->sku,$this->_customerId);
					
					if(!$product){
						$result['message'] = 'SKU: '.$value->sku.'  can not be found.';
						return $result;					
					}
                    if($product['product_status']!='1'){
                        $result['message'] = 'SKU:'.$value->sku.' the product status must be activated.';
                        return $result;
                    }

					$opCategory = 0;
					$cagetory = $productObj->getProductCategory($product['product_id']);
					if($cagetory){
						$opCategory = $cagetory['poc_id'];
					}
					$orderProduct[] =array(										    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $value->quantity,
										   'product_sku' => $product['product_sku'],
										   'op_description' =>$value->refTitle?$value->refTitle:$product['product_title'],	
										   'cn_description' =>$value->refTitleCN?$value->refTitleCN:$product['product_title_cn'],	
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$value->quantity,2),
										   'op_declared_value' => $value->refWorth?$value->refWorth:round($product['product_declared_value']*$value->quantity,2),
										   'op_weight' => round($product['product_weight']*$value->quantity,4),
										   'op_ref_tnx'=>$value->refTxnId?$value->refTxnId:0,
										   'op_ref_item_id'=>$value->refItemId,
										   'op_ref_paydate'=>$value->refPayDate,
											'op_category' => $opCategory,
										   
										);
					$weight += 	round($product['product_weight']*$value->quantity,4);						
					$declaredValue  += 	$value->refWorth?$value->refWorth:round($product['product_declared_value']*$value->quantity,2);
					$parcelContents .=		$product['product_title'].';	';	
					$parcelQty +=	$value->quantity;
				}else{				
					$result['message'] = 'SKU can not be null.';
					return $result;				
				}				 
				$key ++;			
			}		
		}else{
				if($orderDetail->sku){
					$product = $productObj->getProductBySku($orderDetail->sku,$this->_customerId);
					if(!$product){
						$result['message'] = 'SKU: '.$orderDetail->sku.'  can not be found.';
						return $result;					
					}
                    if($product['product_status']!='1'){
                        $result['message'] = 'SKU:'.$orderDetail->sku.' the product status must be activated.';
                        return $result;
                    }

					$opCategory = 0;
					$cagetory = $productObj->getProductCategory($product['product_id']);
					if($cagetory){
						$opCategory = $cagetory['poc_id'];
					}
					$orderProduct[] =array(									    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $orderDetail->quantity,
										   'product_sku' => $product['product_sku'],
										   'op_description' =>$orderDetail->refTitle?$orderDetail->refTitle:$product['product_title'],
										   'cn_description' =>$orderDetail->refTitleCN?$orderDetail->refTitleCN:$product['product_title_cn'],
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_declared_value' => $orderDetail->refWorth?$orderDetail->refWorth:round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_weight' => round($product['product_weight']*$orderDetail->quantity,4),
										   'op_ref_tnx'=>$orderDetail->refTxnId?$orderDetail->refTxnId:0,
										   'op_ref_item_id'=>$orderDetail->refItemId,
										   'op_ref_paydate'=>$orderDetail->refPayDate,
											'op_category' => $opCategory,
										);
					$weight += 	round($product['product_weight']*$orderDetail->quantity,4);				
					$declaredValue += $orderDetail->refWorth?$orderDetail->refWorth:round($product['product_declared_value']*$orderDetail->quantity,2);
					$parcelContents .= 	$product['product_title'];
					$parcelQty +=	$orderDetail->quantity;
				}else{
					$result['message'] = 'SKU can not be null.';
					return $result;
				}
			 
		}
			
		$shipMethod = Default_Service_ShipType::getByValue($shippingMethodCode,$field='st_code');
			
		
		if(!$shipMethod||$shipMethod['st_status']!='1'){
			$result['message'] = 'Shipping method is not Available.';
			return $result;
		}
		
		$options = array('warehouseId'=>1,
						'countryId'=>$countryId,	
						'stId'=>$shipMethod['st_id'],
						'weight'=>$weight,
						'length'=>1,
						'width'=>1,
						'height'=>1,
						'customerId'=>$this->_customerId
						);
		$shipFeeObj = new Default_Service_ShipFeeCalc($options);		
		$fee = $shipFeeObj->calcFeeByType();
		if(!is_array($fee)){
			$result['message'] = $fee;
			return $result;
		}
		//判断是不是存在相同的referenceNo
		$condition = array("customer_id" => $this->_customerId,
				"customer_order_code" => $referenceNo,
				"order_status_arr_not" =>array(0)
		);
		$order = Merchant_Service_Orders::getByCondition($condition);
		
		if(count($order) > 0){
			$result['message'] = "referenceNo $referenceNo exists";
			return $result;
		}				
		
		 $orderInfo = array(     
							'customer_id' =>$this->_customerId,
							'consignee_address1' => $consigneeAddress1,
							'consignee_address2' =>$consigneeAddress2,
							'consignee_city' =>$consigneeCity,
							'consignee_company' =>$consigneeCompany,
							'consignee_country_id' =>$countryId,
							'consignee_email' =>$consigneeEmail,
							'consignee_first_name' =>$consigneeFirstName,
							'consignee_last_name' =>$consigneeLastName,
							'consignee_phone' =>$consigneePhone,
							'consignee_region' =>$consigneeState,
							'consignee_zip' => $consigneeZip,
							'customer_order_code' => $referenceNo,
							'parcel_contents' => !empty($orderContents)?$orderContents:$parcelContents,
							'parcel_declared_value' => $declaredValue,
							'parcel_quantity' => $parcelQty,
							'remark' => $instructions,
							'shipping_method' => $shippingMethodCode,
							'order_product' =>$orderProduct,
							'shipping_fee_estimate' =>$fee['inter_fee'],
							'regAccount'=>$regArr
							);
		
		
		
		$return = Merchant_Service_OrderProccess::addOrder($orderInfo);
		 
		if($return['ask'] == false){
			$result['message'] = join('; ',$return['list']['error']);
			return $result;				
		}
		if(!$orderStatu) $orderStatu = 1;
		$orderCode = $return['ordersCode'];
		 
		$arrStat = array('0','1','2','3');
		if(!in_array($orderStatu,$arrStat)){
			$result['message'] = 'Order status Can not be modify.';
			return $result;
		}
		if($orderStatu>'1'){//交寄订单
			
			$orderPocc = new Merchant_Service_OrderProccess($orderCode);
			$orderPocc->setCustomer($this->_customerId);
			$opStat = $orderPocc->submited($orderCode,$orderStatu);
			
			if($opStat['ask']!='Success'){
				$result['ask'] = 'SuccessWithWarning';			 
				$result['orderCode'] = $orderCode;	
				$result['message'] = 'Warning, change orders status failure, '.$opStat['msg'];
				return $result;	
			}
			
		}
		
		$result['ask'] = 'Success';
		$result['message'] = 'Successful';
		$result['orderCode'] = $orderCode;	 
		
		return $result;	
	}
	
	
	/*
	*
	*getCountry
	*
	*/
	public function getCountry($paramter){	
			$this->_customerId = (string)$paramter->HeaderRequest->customerId;
			$this->_token = (string)$paramter->HeaderRequest->appToken;
			$this->_key = (string)$paramter->HeaderRequest->appKey;
			
			$now = date('Y-m-d H:i:s');
			$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
			$this->authenticate();		
			if(!$this->_auth){
				$result['message'] = $this->_error;
				return $result;		
			}
			$country = Default_Service_Country::getAll();
			
			foreach ($country as $val){
				$arr['countries'][] = $val['en_name'];
			}
			$result['ask'] = 'Success';
			$result['message'] = 'Success.';
			$result['data'] = $arr;
			return $result;
	}
	/*
	*
	*getShippingMethod
	*
	*/
	public function getShippingMethod($paramter){	
			$this->_customerId = (string)$paramter->HeaderRequest->customerId;
			$this->_token = (string)$paramter->HeaderRequest->appToken;
			$this->_key = (string)$paramter->HeaderRequest->appKey;
			
			$now = date('Y-m-d H:i:s');
			$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
			$this->authenticate();		
			if(!$this->_auth){
				$result['message'] = $this->_error;
				return $result;		
			}
			
			$shipTypeObj = new Default_Model_ShipType();
			$condition['st_status'] = 1;
			$shipType = $shipTypeObj->getByCondition($condition);			 
			
			foreach ($shipType as $key => $val){
				$arr[$key]['serviceCode'] = $val['st_code'];
				$arr[$key]['enName'] = $val['st_name'];
				$arr[$key]['cnName'] = $val['st_name_cn'];
				$arr[$key]['deliveryTimeMin'] = $val['st_delivery_time_min'];
				$arr[$key]['deliveryTimeMax'] = $val['st_delivery_time_max'];
			}
		
			$result['ask'] = 'Success';
			$result['message'] = 'Success.';
			$result['data'] = $arr;
			return $result;
	}
	
	/*
	*updateOrder
	*
	*/
	public function updateOrder($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$ordersCode = (string)$paramter->ordersCode;
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','ordersCode'=>$ordersCode,'time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		
		if(!$ordersCode){
			$result['message'] = 'Order code can not be null.';
			return $result;	
		}
		$orders = Merchant_Service_Orders::getByValue($ordersCode,$field='orders_code');
		if(!$orders||empty($orders)){
			$result['message'] = 'Can not find this order. Order Code:'.$ordersCode;
			return $result;			
		}elseif($orders->customer_id != $this->_customerId){
			$result['message'] = 'No permissions.';
			return $result;	
		}
		
		$arrStat = array('0','1','2','3');
		if(!in_array($orders->orders_status,$arrStat)){
			$result['message'] = 'Order status Can not be modify.';
			return $result;
		}
		$consigneeCountry = (string)$paramter->ProductInfo->consigneeCountry;		
		
		//update consignee country
		if($consigneeCountry){
			$countryObj = new Default_Service_Country();
			$countryId = $countryObj->getIdByName($consigneeCountry);
			if(!$countryId){
				$result['message'] = 'Can not find this country.';
				return $result;
			}else{
				$countryId = $orders->consignee_country_id;			
			}		
		}	
		
		$referenceNo = $paramter->orderInfo->referenceNo?$paramter->orderInfo->referenceNo:$orders->customer_order_code;
		$consigneeFirstName = $paramter->orderInfo->consigneeFirstName?$paramter->orderInfo->consigneeFirstName:$orders->consignee_first_name;
		$consigneeLastName = $paramter->orderInfo->consigneeLastName?$paramter->orderInfo->consigneeLastName:$orders->consignee_last_name;
		$consigneeCompany = $paramter->orderInfo->consigneeCompany?$paramter->orderInfo->consigneeCompany:$orders->consignee_company;	
       	$shippingMethodCode =  $paramter->orderInfo->shippingMethodCode?$paramter->orderInfo->shippingMethodCode:$orders->shipping_method;
       	$consigneeZip =  $paramter->orderInfo->consigneeZip?$paramter->orderInfo->consigneeZip:$orders->consignee_zip;
		$consigneeState = $paramter->orderInfo->consigneeState?$paramter->orderInfo->consigneeState:$orders->consignee_region;
		$consigneeCity = $paramter->orderInfo->consigneeCity?$paramter->orderInfo->consigneeCity:$orders->consignee_city;
		$consigneeAddress1 = $paramter->orderInfo->consigneeAddress1?$paramter->orderInfo->consigneeAddress1:$orders->consignee_address1;
       	$consigneeAddress2 = $paramter->orderInfo->consigneeAddress2?$paramter->orderInfo->consigneeAddress2:$orders->consignee_address2;
		$consigneePhone = $paramter->orderInfo->consigneePhone?$paramter->orderInfo->consigneePhone:$orders->consignee_phone;
		
		$consigneeEmail = $paramter->orderInfo->consigneeEmail?$paramter->orderInfo->consigneeEmail:$orders->consignee_email;
       	$instructions = $paramter->orderInfo->instructions?$paramter->orderInfo->instructions:$orders->remark;
		$orderStatu  = $paramter->orderInfo->orderStatu?$paramter->orderInfo->orderStatu:$orders->orders_status;
		
		
		//Order detail
		$orderDetail = $paramter->orderInfo->orderDetail;	
		$key = 0;
		$productObj = new Merchant_Service_Product();
		$parcelContents = '';
		$declaredValue = 0;
		$parcelQty  = 0;
		
		if (count($orderDetail) > 1) {
			foreach ($orderDetail as $value) {			 
				if($value->sku){
					$product = $productObj->getProductBySku($value->sku);
					if(!$product){
						$result['message'] = 'SKU: '.$value->sku.'  can not be found.';
						return $result;				
					}
					$orderProduct[] = array(			    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $value->quantity,
										   'product_sku' => $product['product_sku'],
										   'op_description' => $product['product_title'],
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$value->quantity,2),
										   'op_declared_value' => round($product['product_declared_value']*$value->quantity,2),
										   'op_weight' => round($product['product_weight']*$value->quantity,2),
										);
					$declaredValue  += 	round($product['product_declared_value']*$value->quantity,2);				
					$parcelContents .=		$product['product_title'].';	';	
					$parcelQty +=	$value->quantity;
				}else{				
					$result['message'] = 'SKU can not be null.';
					return $result;				
				}				 
				$key ++;			
			}		
		}elseif(count($orderDetail) == 1){			
				if($orderDetail->sku){
					$product = $productObj->getProductBySku($orderDetail->sku);
					if(!$product){
						$result['message'] = 'SKU: '.$orderDetail->sku.'  can not be found.';
						return $result;					
					}
					$orderProduct[] =array(										    
										   'product_id' => $product['product_id'],										  
										   'op_quantity' => $orderDetail->quantity,
										   'product_sku' => $product['product_sku'],
										   'op_description' => $product['product_title'],
										   'op_unit_price' => $product['product_declared_value'],
										   'op_subtotal' => round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_declared_value' => round($product['product_declared_value']*$orderDetail->quantity,2),
										   'op_weight' => round($product['product_weight']*$orderDetail->quantity,2),
										);
					$declaredValue += round($product['product_declared_value']*$orderDetail->quantity,2);
					$parcelContents .= 	$product['product_title'];
					$parcelQty +=	$orderDetail->quantity;
				}else{				
					$result['message'] = 'SKU can not be null.';
					return $result;				
				}
		}else{		
			$declaredValue  = $orders->parcel_declared_value;
			$parcelContents = $orders->parcelContents;
			$parcelQty 		= $orders->parcel_quantity;
		}
		
		
		
		
		$orderInfo =array(        
			'order_id'=>$orders->order_id,
            'customer_id' =>$this->_customerId,
            'consignee_address1' => $consigneeAddress1,
            'consignee_address2' =>$consigneeAddress2,
            'consignee_city' =>$consigneeCity,
            'consignee_company' =>$consigneeCompany,
            'consignee_country_id' =>$countryId,
            'consignee_email' =>$consigneeEmail,
            'consignee_first_name' =>$consigneeFirstName,
            'consignee_last_name' =>$consigneeLastName,
            'consignee_phone' =>$consigneePhone,
            //'consignee_region' =>$consignee_region,
            'consignee_zip' => $consigneeZip,
            'customer_order_code' => $referenceNo,
            'parcel_contents' => $parcelContents,
            'parcel_declared_value' => $declaredValue,
            'parcel_quantity' => $parcelQty,
            'remark' => $instructions,
            'shipping_method' => $shippingMethodCode,
            'order_product' =>$orderProduct,
            'shipping_fee_estimate' =>0
        );
		
		$result = Merchant_Service_OrderProccess::edit($orderInfo);
		$str = var_export($result,true);
		self::logError($str);
		$return['message'] = $result['list']['message'];
		if($result['ask'] == false){
			
			return $return;				
		}
		 
		$return['ask'] = 'Success.';
		 
		return $return; 
	}

	/*
	*
	*getOrderByCode
	*
	*/
	public function getOrderByCode($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$ordersCode = (string)$paramter->ordersCode;
		$detailLevel = (string)$paramter->detailLevel;
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		
		if(!$ordersCode){
			$result['message'] = 'Order code can not be null.';
			return $result;	
		}
		$orders = Merchant_Service_Orders::getByValue($ordersCode,$field='orders_code');
		 
		if(!$orders||empty($orders)){
			$result['message'] = 'Can not find this order. Order Code:'.$ordersCode;
			return $result;			
		}elseif($orders['customer_id'] != $this->_customerId){
			$result['message'] = 'No permissions.';
			return $result;	
		}
		$warehouse = Merchant_Service_Warehouse::getDetail($orders['warehouse_id']);
		if($orders['orders_status']>4){//需求要求CFF发货后返回
			$orderShip = Merchant_Service_OrderShip::getByValue($ordersCode,$field='orders_code');	
			$trackNumber = $orderShip['tracking_number'];
			$refTrackNumber = '';
			if($orderShip['orders_code']!=$orderShip['ref_tracking_number']){
				$refTrackNumber = $orderShip['ref_tracking_number'];
			}
			$carrierCode = $orderShip['carrier_code'];
			$shippingFee = $orderShip['os_shipping_fee'];
			$currencyCode = $orderShip['currency_code'];
			$parcelWeight = $orderShip['os_weight'];
			$sendDate = $orderShip['os_send_date'];
		}
		$data = array(
						'ordersCode'=>$orders['orders_code'],//订单编号
						'warehouse'=>$warehouse['warehouse_name'],
						'consigneeFirstName'=>$orders['consignee_first_name'],
						'consigneeLastName'=>$orders['consignee_last_name'],
						'consigneeCompany'=>$orders['consignee_company'],
						'consigneeZip'=>$orders['consignee_zip'],
						'consigneeRegion'=>$orders['consignee_region'],
						'consigneeCity'=>$orders['consignee_city'],
						'consigneeAddress1'=>$orders['consignee_address1'],
						'consigneeAddress2'=>$orders['consignee_address2'],
						'consigneePhone'=>$orders['consignee_phone'],
						'consigneeEmail'=>$orders['consignee_email'],
						'shippingMethod'=>$orders['shipping_method'],
						'parcelDeclaredValue'=>$orders['parcel_declared_value'],
						'parcelContents'=>$orders['parcel_contents'],
						'parcelQuantity'=>$orders['parcel_quantity'],
						'ordersStatus'=>$orders['orders_status'],
						'problemStatus'=>$orders['problem_status'],
						'shippingFeeEstimate'=>$orders['shipping_fee_estimate'],
						'referenceNo'=>$orders['customer_order_code'],
						'createTime'=>$orders['add_time'],
						 
						'shipDate'=>$orders['ship_date'],
						'sendDate'=>$sendDate,
						'deliveredDate'=>$orders['delivered_date'],
						'trackingNumber'=>$trackNumber,
						'refTrackingNumber'=>$refTrackNumber,
						'carrierCode'=>$carrierCode,
						'shippingFee'=>$shippingFee,
						'currencyCode'=>$currencyCode,
						'parcelWeight'=>$parcelWeight
						
					);
			
		if($detailLevel==1){		
			$condition["orders_code"] = $orders['orders_code'];
			$orderProduct = Merchant_Service_OrderProduct::getByCondition($condition);
		
			foreach ($orderProduct as $val){
						$data['orderProduct'][] = array(
													 
													'productSku'=>$val['product_sku'],
													'productTitle'=>$val['op_title'],
													'quantity'=>$val['op_quantity'],
													'weight'=>$val['weight'],
													'unitPrice'=>$val['op_unit_price'],
													'subtotal'=>$val['op_subtotal'],
													'declaredValue'=>$val['op_declared_value'],
													'categoryId'=>$val['op_category'] 
													);
			
			}
		}
		
		$result['ask'] = 'Success';
		$result['message'] = 'Success.';
		$result['data'] = $data;
		return $result;
	
	}
	/*
	*
	*getOrderByCode
	*
	*/
	public function getOrders($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		
	 	
		$now = date('Y-m-d H:i:s');
		$result = array('ask'=>'Error','message'=>'','data'=>'','time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}
		$condition = array();
		
		 
		 
		 
		if($paramter->createTime->start) $condition["add_time_start"] =  $paramter->createTime->start;
		if($paramter->createTime->end) $condition["add_time_end"] =  $paramter->createTime->end;
		
		if($paramter->submitTime->start) $condition['submit_time_start'] =  $paramter->submitTime->start;
		if($paramter->submitTime->start) $condition['submit_time_end'] =  $paramter->submitTime->end;
		
		if($paramter->sentTime->start) $condition['ship_date_start'] =  $paramter->sentTime->start;
		if($paramter->sentTime->start) $condition['ship_date_end'] =  $paramter->sentTime->end;
		
		if($paramter->status) $condition['orders_status'] = $paramter->status;
		if($paramter->problemStatus) $condition['problem_status'] = $paramter->problemStatus;
		
		if($paramter->ordersCode) $condition['orders_code'] = $paramter->ordersCode;
		if($paramter->referenceNo) $condition['customer_order_code'] = $paramter->referenceNo;
		if($paramter->shippingMethod) $condition['shipping_method'] = $paramter->shippingMethod;
		if($paramter->destinationCountry){
			$countryObj = new Default_Service_Country();
			$countryId = $countryObj->getIdByName($paramter->destinationCountry);
			if(!$countryId){
				$result['message'] = 'Can not find this country.';
				return $result;
			}
			$condition["consignee_country_id"] =$countryId;
		 
		
		}
		$pageSize = $paramter->steps->pageSize;
		$page = $paramter->steps->page;
		
		if(empty($condition)&$pageSize==null){
			$pageSize	 = 100;
			$page	 = 1;		
		}
		
		$condition["customer_id"] = $this->_customerId;
		$detailLevel  = $paramter->detailLevel;
		$orderList = Merchant_Service_Orders::getByCondition($condition,$type='*',$page,$pageSize,0);
		
		if(!$orderList||empty($orderList)){
			$result['message'] = 'no data. ';
			return $result;			
		} 
		foreach($orderList as $key => $orders){
			
			$warehouse = Merchant_Service_Warehouse::getDetail($orders['warehouse_id']);
			
			if($orders['orders_status']>4){//订单已发出后
				$orderShip = Merchant_Service_OrderShip::getByValue($orders['orders_code'],$field='orders_code');	
				$trackNumber = $orderShip['tracking_number'];
				$refTrackNumber = '';
				if($orderShip['orders_code']!=$orderShip['ref_tracking_number']){
					$refTrackNumber = $orderShip['ref_tracking_number'];
				}
				$carrierCode = $orderShip['carrier_code'];
				$shippingFee = $orderShip['os_shipping_fee'];
				$currencyCode = $orderShip['currency_code'];
				$parcelWeight = $orderShip['os_weight'];
				$sendDate = $orderShip['os_send_date'];
			}
			$data[$key] = array(
							'ordersCode'=>$orders['orders_code'],//订单编号
							'warehouse'=>$warehouse['warehouse_name'],
							'consigneeFirstName'=>$orders['consignee_first_name'],
							'consigneeLastName'=>$orders['consignee_last_name'],
							'consigneeCompany'=>$orders['consignee_company'],
							'consigneeZip'=>$orders['consignee_zip'],
							'consigneeRegion'=>$orders['consignee_region'],
							'consigneeCity'=>$orders['consignee_city'],
							'consigneeAddress1'=>$orders['consignee_address1'],
							'consigneeAddress2'=>$orders['consignee_address2'],
							'consigneePhone'=>$orders['consignee_phone'],
							'consigneeEmail'=>$orders['consignee_email'],
							'shippingMethod'=>$orders['shipping_method'],
							'parcelDeclaredValue'=>$orders['parcel_declared_value'],
							'parcelContents'=>$orders['parcel_contents'],
							'parcelQuantity'=>$orders['parcel_quantity'],
							'ordersStatus'=>$orders['orders_status'],
							'problemStatus'=>$orders['problem_status'],
							'shippingFeeEstimate'=>$orders['shipping_fee_estimate'],
							'referenceNo'=>$orders['customer_order_code'],
							'createTime'=>$orders['add_time'],
							 
							'shipDate'=>$orders['ship_date'],
							'sendDate'=>$sendDate,
							'deliveredDate'=>$orders['delivered_date'],
							'trackingNumber'=>$trackNumber,
							'refTrackingNumber'=>$refTrackNumber,
							'carrierCode'=>$carrierCode,
							'shippingFee'=>$shippingFee,
							'currencyCode'=>$currencyCode,
							'parcelWeight'=>$parcelWeight
							
						);
			
			if($detailLevel==1){		
				$condition["orders_code"] = $orders['orders_code'];
				$orderProduct = Merchant_Service_OrderProduct::getByCondition($condition);
				foreach ($orderProduct as $val){
							$data[$key]['orderProduct'][] = array(
														 
														'productSku'=>$val['product_sku'],
														'productTitle'=>$val['op_title'],
														'quantity'=>$val['op_quantity'],
														'weight'=>$val['weight'],
														'unitPrice'=>$val['op_unit_price'],
														'subtotal'=>$val['op_subtotal'],
														'declaredValue'=>$val['op_declared_value'],
														'categoryId'=>$val['op_category'] 
														);
				
				}
			}
		
		}
		
		
		$result['ask'] = 'Success';
		$result['message'] = 'Success.';
		$result['data'] = $data; 
		return $result;
		 
	}
	
	
	
	/*
	*
	*updateOrderStatu
	*/
	public function updateOrderStatu($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$now = date('Y-m-d H:i:s');
		$ordersCode = (string)$paramter->ordersCode;
		$result = array('ask'=>'Error','message'=>'','ordersCode'=>$ordersCode,'time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}		
		$statu = (int)$paramter->statu;
		//:0 删除,1 草稿,2 已确认,3 On Hold
		$statArr = array(0,1,2,3);
		if(!in_array($statu,$statArr)){
			$result['message'] = 'Order statu is not allow. ';
			return $result;		
		}		
		
		if(!$ordersCode){
			$result['message'] = 'Order code can not be null.';
			return $result;	
		}
		$orderObj = new Merchant_Service_OrderProccess();
		 
		$orderObj->setCustomer($this->_customerId);
		$return = $orderObj->submited($ordersCode,$statu,true,true);//强制扣款
		
		if($return['ask']=='Error'){
			
			$result['message'] = $return['msg'];
			return $result;
		}
		$result['message'] = 'Success';
		$result['ask'] = 'Success';
		return $result;
		
	
	}
	/*
	*
	* Authenticate
	*/
	
	private function authenticate(){
		$customerAuthObj = new Default_Model_CustomerAuthenticate();
		$customerAuth = $customerAuthObj->getByValue($this->_customerId,'customer_id');
		
		if($customerAuth['ca_token']==$this->_token&$customerAuth['ca_key']==$this->_key){
			$this->_auth = true;
			return true;
		}
		$this->_error = 'App Token/App Key Not match for '.$this->_customerId.'.';
		return false;
	}
	private function logError($error){
	
		//$str = var_export($return,true);
		//self::logError($str);
    	$logger = new Zend_Log();
		$uploadDir = APPLICATION_PATH."/../data/log/";
		$writer = new Zend_Log_Writer_Stream($uploadDir.'api.log');
		$logger->addWriter($writer);
		$logger->info(date('Y-m-d H:i:s').': '.$error." \n");
    }
	
	/*
	*
	*StopOrder
	*/
	public function stopOrder($paramter){
		$this->_customerId = (string)$paramter->HeaderRequest->customerId;
		$this->_token = (string)$paramter->HeaderRequest->appToken;
		$this->_key = (string)$paramter->HeaderRequest->appKey;
		$now = date('Y-m-d H:i:s');
		$ordersCode = (string)$paramter->ordersCode;
		$result = array('ask'=>'Error','message'=>'','ordersCode'=>$ordersCode,'time'=>$now);
		$this->authenticate();		
		if(!$this->_auth){
			$result['message'] = $this->_error;
			return $result;		
		}		
		$return =  Merchant_Service_Orders::stop($ordersCode,$this->_customerId); 
		$result['message'] = $return['message'];
		if($return['ask']=='Error'){ 
			return $result;
		} 
		$result['ask'] = $return['ask'];
		return $result;
		
	
	}


}